<template>
    <div
        class="jzyong_avatar"
        :style="{
            width: size,
            height: size,
            borderRadius: (() => {
                   switch (mode) {
                       case 'square': return 'none'
                       case 'square-r': return '4px'
                       case 'round': return '50%'
                   }
            })(),
            backgroundColor: backgroundColor
    }">
        <img
            ref="image"
            :src="src"
            :alt="alt"
            :style="{
                objectFit: autoWH ? 'none' : fit
            }"
            @load="load"
            @error="error"
        />
    </div>
</template>

<script>
import './style.less'

export default {
    name: 'jzyongAvatar',
    props: {
        // 宽高
        size: {
            type: String,
            default: '48px'
        },

        // 图片链接
        src: {
            type: String,
            required: true
        },

        // 原生alt属性
        alt: String,

        // 头像形状
        mode: {
            type: String,
            default: 'round',
            validator: (value) => {
                // 正方形，带圆角正方形，圆形
                return ['square', 'square-r', 'round'].indexOf(value) !== -1
            }
        },

        // css: object-fit
        fit: {
            type: String,
            default: 'cover',
            validator: (value) => {
                return [
                    'fill', 'contain', 'cover',
                    'none', 'scale-down', 'initial',
                    'inherit'
                ].indexOf(value) !== -1
            }
        },

        // 自动宽高
        autoWH: {
            type: Boolean,
            default: false
        },

        backgroundColor: {
            type: String,
            default: 'rgbe(0, 0, 0, 0)'
        }
    },
    data() {
        return {}
    },
    methods: {

        // 图片加载完成事件
        load(e) {
            this.$emit('load', {event: e, vm: this})

            if (this.autoWH) {
                const {width, height} = getComputedStyle(this.$refs.image)

                if (width > height) {
                    this.$refs.image.style.width = '100%';
                } else if (width < height) {
                    this.$refs.image.style.height = '100%';
                } else {
                    this.$refs.image.style.width = '100%';
                    this.$refs.image.style.height = '100%';
                }
            }
        },

        // 图片加载失败事件
        error(e) {
            this.$emit('error', {event: e, vm: this})
        }
    }
}
</script>
